package com.example.administrator.myview.util;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.webkit.MimeTypeMap;

import java.io.File;


import sjj.permission.PermissionCallback;
import sjj.permission.model.Permission;
import sjj.permission.util.PermissionUtil;

import static android.content.Context.DOWNLOAD_SERVICE;

/**
 * Created by administrator on 2017/6/8.
 */

public class DownLoadFile {
    private String downLoadUrlStr = "";
    private Context mContext = null;						//调用窗体句柄
    private String mSavePath = "";
    public DownLoadFile(Context content, String urlStr){
        mContext = content;
        downLoadUrlStr = urlStr;
        content.registerReceiver(downloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        PermissionUtil.requestPermissions((Activity) mContext, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                new PermissionCallback() {
                    @Override
                    public void onGranted(Permission permissions) {
                        downloadApk();
                    }

                    @Override
                    public void onDenied(Permission permissions) {

                    }
                });

    }

    private BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            /**下载完成后安装APK**/
            installApk();
        }
    };

    private void downloadApk() {
        // 判断SD卡是否存在，并且是否具有读写权限
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                mSavePath = Environment.getExternalStorageDirectory() + "/Download/";
                File dir = new File(mSavePath);
                if(!dir.exists()) dir.mkdirs();	//没有目录就创建
                String apkUrl = downLoadUrlStr;
                Uri uri = Uri.parse(apkUrl);
                DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE);
                DownloadManager.Request request = new DownloadManager.Request(uri);
                // 设置允许使用的网络类型，这里是移动网络和wifi都可以
                request.setAllowedNetworkTypes(request.NETWORK_MOBILE | request.NETWORK_WIFI);
                //设置是否允许漫游
                request.setAllowedOverRoaming(false);
                //设置文件类型
                MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
                String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(apkUrl));
                request.setMimeType(mimeString);
                //在通知栏中显示
                request.setNotificationVisibility(request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setTitle("download...");
                request.setVisibleInDownloadsUi(true);
                //sdcard目录下的download文件夹
                request.setDestinationInExternalPublicDir("/Download", "qh2298_seller_android.apk");
                mSavePath += "qh2298_seller_android.apk";
                // 将下载请求放入队列
                downloadManager.enqueue(request);
            }
        }catch (Exception ignored){

        }
    }

    //安装apk
    private void installApk() {
        Intent i = new Intent(Intent.ACTION_VIEW);
        File dir = new File(mSavePath);
        if(Build.VERSION.SDK_INT>=24) { //判读版本是否在7.0以上
            Uri apkUri =
                    FileProvider.getUriForFile(mContext, "com.qh.qh2298.provider",  dir);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            i.setDataAndType(apkUri, "application/vnd.android.package-archive");
        }else {
            i.setDataAndType(Uri.parse("file://" + mSavePath), "application/vnd.android.package-archive");
        }
        mContext.startActivity(i);
    }
}

